package com.sycu.socket.unit07;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class TCPClient {
    public static void main(String[] args) {
        final String DEFAULT_SERVER_HOST = "127.0.0.1";
        final int DEFAULT_PORT = 8888;
        Socket socket = null;
        BufferedWriter writer = null;
        BufferedReader reader = null;

        try {
            // 创建 socket
            socket = new Socket(DEFAULT_SERVER_HOST, DEFAULT_PORT);

            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

            // 上传 A.html 文件到服务器
            BufferedWriter fileWriter = new BufferedWriter(writer);
            BufferedReader fileReader = new BufferedReader(new FileReader("A.html"));
            fileWriter.write("START_UPLOAD\n");
            fileWriter.flush();
            String line;
            while ((line = fileReader.readLine())!= null) {
                fileWriter.write(line + "\n");
                fileWriter.flush();
            }
            fileWriter.write("END_UPLOAD\n");
            fileWriter.flush();
            fileReader.close();

            // 等待服务器确认上传成功
            String msg = reader.readLine();
            System.out.println(msg);

            // 下载 C.html 文件内容并保存到 D.html
            writer.write("START_DOWNLOAD\n");
            writer.flush();
            msg = reader.readLine();
            if ("SERVER_SENDING_FILE".equals(msg)) {
                BufferedWriter fileWriterD = new BufferedWriter(new FileWriter("D.html"));
                while ((msg = reader.readLine())!= null &&!"END_DOWNLOAD".equals(msg)) {
                    fileWriterD.write(msg + "\n");
                    fileWriterD.flush();
                }
                fileWriterD.close();
                System.out.println("文件下载成功");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer!= null) {
                try {
                    reader.close();
                    writer.close();
                    System.out.println("关闭 socket");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!= null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}